clear all
use "../processed/GHS_aggr", clear

local mined = 5 // min year
local maxed = 20 // max year
gen yschl = min(agelfted-5,`maxed')
tab yschl [fw=nobs], m

egen cy = group(datyear yearat14) // cohort-year group for clustering
sum cy, d

local ctrl
forvalues j=1/4{
	local ctrl `ctrl' age_`j' yearat14_`j'
}

local ny = 6
matrix A = J(`ny',8,.)
mat colnames A = w_pop w_pop_se w_ols w_ols_se w_iv w_iv_se b_ols b_ols_se

// compute birth cohort weight
gen c1 = ( yearat14<=40 )
gen c2 = ( yearat14>40 & yearat14<=45 )
gen c3 = ( yearat14>45 & yearat14<=50 )
gen c4 = ( yearat14>50 & yearat14<=55 )
gen c5 = ( yearat14>55 & yearat14<=60 )
gen c6 = ( yearat14>60 )

reg yschl `ctrl' [fw=nobs]
predict xres, resid
reg drop15 `ctrl' [fw=nobs]
predict zres, resid
matrix define b_ini = e(b)
gen xz = yschl*zres
reg xz `ctrl' [fw=nobs]
matrix define b_ini = (b_ini,e(b),0)

local vce vce(cluster cy)
forvalues j=1/6{
	reg c`j' [fw=nobs], `vce'
	matrix A[`j',1] =  _b[_cons]
	matrix A[`j',2] = _se[_cons]
	gen w`j' = c`j'*xres
	reg w`j' xres [fw=nobs], `vce'
	matrix A[`j',3] =  _b[xres]
	matrix A[`j',4] = _se[xres]	
	gmm (z:drop15-{zb:`ctrl' _cons}) (r:yschl*(drop15-{zb:})-{xb:`ctrl' _cons}) (e`j':(c`j'-{w`j'})*{xb:}) [fw=nobs], ///
	inst(z:`ctrl') deriv(z/zb=-1) inst(r:`ctrl') deriv(r/xb=-1) deriv(r/zb=-yschl) ///
	inst(e`j':) deriv(e`j'/xb=c`j'-{w`j'}) deriv(e`j'/w`j'=-{xb:}) onestep winit(i) `vce' from(b_ini)
	matrix A[`j',5] =  _b[/w`j']
	matrix A[`j',6] = _se[/w`j']
	reg learn yschl `ctrl' if c`j'==1 [fw=nobs], `vce'
	matrix A[`j',7] =  _b[yschl]
	matrix A[`j',8] = _se[yschl]	
}

preserve
clear
svmat A, names(col)
gen cohort = _n
order cohort, first
export delimited using ../result/wgt_w.csv, replace
restore

// compute treatment-level weights
local ny = `maxed' - `mined' + 1
matrix B = J(`ny',8,.)
mat colnames B = w_pop w_pop_se w_ols w_ols_se w_iv w_iv_se b_ols b_ols_se
local op `"[fw=nobs], vce(cluster cy)"'
forvalues j=`mined'/`maxed'{
	gen d`j' = yschl==`j'
	reg d`j' `op'
	matrix B[`j'-`mined'+1,1] =  _b[_cons]
	matrix B[`j'-`mined'+1,2] = _se[_cons]	
	if ( `j'>`mined' ){
		gen x`j' = (yschl>=`j')
		reg x`j' yschl `ctrl' `op'
		matrix B[`j'-`mined'+1,3] =  _b[yschl]
		matrix B[`j'-`mined'+1,4] = _se[yschl]			
		ivregress 2sls x`j' (yschl=drop15) `ctrl' `op'
		matrix B[`j'-`mined'+1,5] =  _b[yschl]
		matrix B[`j'-`mined'+1,6] = _se[yschl]	
		reg learn yschl `ctrl' if yschl==`j' | yschl==`j'-1 `op'
		matrix B[`j'-`mined'+1,7] =  _b[yschl]
		matrix B[`j'-`mined'+1,8] = _se[yschl]		
	}
}
preserve
clear
svmat B, names(col)
gen x = _n+4
order x, first
export delimited using ../result/wgt_x.csv, replace
restore
